package com.wenyl.juc.thread.forkJoinTest;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author Swimming Dragon
 * @description: TODO
 * @date 2024年11月07日 11:26
 */
public class CountTask extends RecursiveTask<Integer> {
    private int start;
    private int end;
    private static final int TASKSIZE = 2;
    private static int count = 2;
    public CountTask(int start,int end){
        this.start = start;
        this.end = end;
    }
    @Override
    protected Integer compute() {
        int sum = 0;
        System.out.println("开启线程进行计算"+count++);
        boolean flag = (this.end-this.start)<=TASKSIZE;
        if(flag){
            for(int i=this.start;i<=this.end;i++){
                sum += i;
            }
        }else{
            System.out.println("这个任务需要拆分计算..."+Thread.currentThread().getName());
            int middle = (this.start+this.end)/2;
            CountTask countTask1 = new CountTask(this.start,middle);
            CountTask countTask2 = new CountTask(middle+1,this.end);
            invokeAll(countTask1,countTask2);
            Integer taskSum1 = countTask1.join();
            Integer taskSum2 = countTask2.join();
            sum = taskSum1+taskSum2;

        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        CountTask countTask = new CountTask(1,100);
        ForkJoinTask<Integer> forkJoinTask = pool.submit(countTask);
        try {
            System.out.println(forkJoinTask.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
